﻿using NPOI.XWPF.UserModel;// 解析word
using Microsoft.Office.Core;// 解析ppt
using PowerPoint = Microsoft.Office.Interop.PowerPoint;// 解析ppt
using UglyToad.PdfPig.Content;// 解析pdf
using UglyToad.PdfPig; //解析pdf
using SimpleDesktop.Plugins.EveryThing;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System.IO.Enumeration;


namespace myFileWatcher
{
    // 自定义文件事件类型
    public class FileEvent
    {
        public int changeType { get; set; }
        public string path { get; set; }
    }

    public enum ChangeType : int
    {
        CHANGED = 0,
        CREATED = 1,
        DELETED = 2,
        LOG = 3
    }
    internal class Utility
    {
        // 展示已打开文件
        public static void showopenFile(RichTextBox richTextBox, List<string> Files)
        {
            richTextBox.Clear();
            for (int i = 0; i < Files.Count; i++)
            {
                richTextBox.AppendText(Files[i]+'\n');
            }
        }
        //获取已打开文件和无访问权限的文件
        public static (List<string> OpenFiles, List<string> NoAccessFiles) CheckFilesAndPermissions(string rootPath)
        {
            var openFiles = new List<string>();
            var noAccessFiles = new List<string>();

            void TraverseDirectory(string path)
            {
                try
                {
                    foreach (var file in Directory.GetFiles(path))
                    {
                        try {
                     
                            using (FileStream stream = new FileStream(file, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
                            {
                                // 文件可以被打开（注意：这里逻辑上应当表示文件未被其他进程以独占方式打开，但按任务要求记录"被打开"的逻辑应调整）
                            }
                        }
                        catch (IOException) // 文件被占用
                        {
                            openFiles.Add(file);
                        }
                        catch (UnauthorizedAccessException) // 没有访问权限
                        {
                            noAccessFiles.Add(file);
                        }
                    }
                }
                catch (DirectoryNotFoundException)
                {
                    Console.WriteLine($"目录未找到: {path}");
                }

                foreach (var subDir in Directory.GetDirectories(path))
                {
                    TraverseDirectory(subDir);
                }
            }

            TraverseDirectory(rootPath);
            return (openFiles, noAccessFiles);
        }

        // 用于递归
        public static void LoadTreeViewWithDirectories(TreeNode rootNode, string rootPath)
        {

            try
            {
                // 遍历目录
                foreach (string directory in Directory.GetDirectories(rootPath))
                {
                    TreeNode node = new TreeNode(Path.GetFileName(directory));
                    node.Tag = directory; // 存储完整路径以便后续使用
                    node.ImageIndex = 1; // 文件夹图标索引
                    node.SelectedImageIndex = 1;
                    rootNode.Nodes.Add(node);
                    LoadTreeViewWithDirectories(node, directory); // 递归加载子目录
                }

                foreach (string file in Directory.GetFiles(rootPath))
                {
                    TreeNode fileNode = new TreeNode(Path.GetFileName(file));
                    fileNode.Tag = file; // 存储文件完整路径
                    fileNode.ImageIndex = 0; // 文件图标索引，同样需配置ImageList
                    fileNode.SelectedImageIndex = 0;
                    rootNode.Nodes.Add(fileNode);
                }
            }
            catch (UnauthorizedAccessException)
            {
                // 处理无权限访问的异常，比如某些受保护的系统文件夹
                TreeNode errorNode = new TreeNode("[无权限访问]");
                rootNode.Nodes.Add(errorNode);
            }
        }

        // 调用递归
        public static void LoadTreeViewWithDirectories(TreeView treeView, string rootPath)
        {
            treeView.Nodes.Clear();
            TreeNode rootNode = new TreeNode(rootPath);
            treeView.Nodes.Add(rootNode);
            rootNode.ImageIndex = 2; // 文件夹图标索引，需事先配置ImageList
            rootNode.SelectedImageIndex = 2;

            LoadTreeViewWithDirectories(rootNode, rootPath);

        }
        // 根据关键词查找相关文件
        public static void SearchEverything(string searchString, ListView listView)
        {
            EveryThing64.Everything_SetSearchW(searchString);
            EveryThing64.Everything_SetMatchPath(true);
            EveryThing64.Everything_SetMatchCase(false);
            EveryThing64.Everything_SetMatchWholeWord(false);
            EveryThing64.Everything_SetRegex(false);
            EveryThing64.Everything_SetMax(1); // 限制结果数量

            if (EveryThing64.Everything_Query(true))
            {
                int numResults = (int)EveryThing64.Everything_GetNumResults();
                //listView.Items.Clear();

                for (uint i = 0; i < numResults; i++)
                {
                    StringBuilder resultPath = new StringBuilder(260);
                    EveryThing64.Everything_GetResultFullPathName(i, resultPath, 260);
                    string path = resultPath.ToString();

                    string name = System.IO.Path.GetFileName(path);
                    string type = EveryThing64.Everything_IsFolderResult(i) ? "Folder" : "File";

                    ListViewItem item = new ListViewItem(name);
                    item.SubItems.Add(path);
                    item.SubItems.Add(type);
                    listView.Items.Add(item);
                }
            }
            else
            {
                
                MessageBox.Show("暂无推荐");
            }
        }
        // 读取word
        public static string getTextfromWord(string WordfilePath)
        {
            if (!File.Exists(WordfilePath))
            {
                return "";
            }
            StringBuilder Text = new StringBuilder();
            
            try
            {
                // 加载Word文档
                using (FileStream fileStream = new FileStream(WordfilePath, FileMode.Open, FileAccess.Read))
                {
                    XWPFDocument document = new XWPFDocument(fileStream);

                    // 遍历文档中的每个段落
                    foreach (XWPFParagraph paragraph in document.Paragraphs)
                    {
                        // 获取段落文本并转换为小写以便比较
                        Text.Append(paragraph.Text.ToLower());

                    }

                    // 记得关闭文档流
                    fileStream.Close();
                }
            }
            catch (Exception ex)
            {
                //Console.WriteLine($"Error occurred: {ex.Message}");
            }
            return Text.ToString();
        }

        // 读取ppt
        public static string getTextfromPowerPoint(string PowerPointfilePath)
        {
            StringBuilder Text = new StringBuilder(2048);
            if (!File.Exists(PowerPointfilePath)) {
                return "";
            }
            // 初始化PowerPoint应用程序
            PowerPoint.Application pptApp = new PowerPoint.Application();
            try
            {
                // 打开PPT文件
                PowerPoint.Presentations pres = pptApp.Presentations;
                PowerPoint.Presentation pptPres = pres.Open(PowerPointfilePath, MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoFalse);

                // 遍历所有幻灯片
                for (int i = 1; i <= pptPres.Slides.Count; i++)
                {
                    PowerPoint.Slide slide = pptPres.Slides[i];

                    // 遍历幻灯片中的所有文本框
                    foreach (Microsoft.Office.Interop.PowerPoint.Shape shape in slide.Shapes)
                    {
                        if (shape.HasTextFrame.Equals(false)) continue;

                        // 确保文本框中有文本
                        if (shape.TextFrame.HasText.Equals(false)) continue;

                        // 读取文本
                        Text.Append(shape.TextFrame.TextRange.Text.ToString());

                    }
                }
            }
            finally
            {
                // 清理并退出PowerPoint应用程序
                if (pptApp != null)
                {
                    Marshal.ReleaseComObject(pptApp);
                }
            }


            return Text.ToString();
        }
        // 读取pdf
        public static string getTextfromPDF(string PDFfilePath)
        {
            StringBuilder Text = new StringBuilder();

            using (PdfDocument document = PdfDocument.Open(PDFfilePath))
            {
                foreach (Page page in document.GetPages())
                {
                    string pageText = page.Text;

                    foreach (Word word in page.GetWords())
                    {
                        Text.Append(word.Text);
                    }
                }
            }

            return Text.ToString();
        }

        // 提取最高频次的词组
        public static string[] ExtractKeywords(IEnumerable<string> words, int topN)
        {

            // 创建一个字典来统计每个单词的出现频率
            Dictionary<string, int> wordCounts = new Dictionary<string, int>();
            foreach (string word in words)
            {
                if (word.Length > 1) // 忽略长度为1的单词，通常是停用词
                {
                    if (wordCounts.ContainsKey(word))
                    {
                        wordCounts[word]++;
                    }
                    else
                    {
                        wordCounts.Add(word, 1);
                    }
                }
            }

            // 根据频率对单词进行排序
            List<KeyValuePair<string, int>> sortedWords = wordCounts.ToList();
            sortedWords.Sort((x, y) => y.Value.CompareTo(x.Value));

            // 获取出现频率最高的前N个单词
            string[] topKeywords = sortedWords.Take(topN)
                                                .Select(pair => pair.Key)
                                                .ToArray();

            return topKeywords;
        }
    }

}


